<script setup lang="ts">
  import { computed, h, ref } from 'vue'
  import { ElDivider } from 'element-plus'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import goodSelectModal from './good-select-modal.vue'
  import { SelectedGood } from '../../types'

  defineOptions({
    name: 'ChargeStandardsByGood',
  })

  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const selectGoodDrawerVisible = ref(false)
  const selectedGoods = ref<Array<SelectedGood>>([])
  const removedFeeStandardIds = ref<Array<string>>([])
  const selectedGoodIds = computed(() => {
    return selectedGoods.value.map((good) => {
      return {
        goodId: good.goodId,
        goodSpecId: good.goodSpecId,
      }
    })
  })

  // 支付网点费用（用于给所有产品都填充上去）
  const allPayNetworkFee = ref('0')

  /**
   * 产品添加事件
   * @param {Array<SelectedGood>} goods - 要添加的产品列表
   */
  const handleGoodAdd = (goods: Array<SelectedGood>) => {
    if (goods.length === 0) {
      selectedGoods.value.forEach((item) => {
        if (item.id && !removedFeeStandardIds.value.includes(item.id)) {
          removedFeeStandardIds.value.push(item.id)
        }
      })
      selectedGoods.value.length = 0
    }

    goods.forEach((good) => {
      const goodIds = selectedGoods.value.map((selectGood) => selectGood.goodId)
      const goodSpecIds = selectedGoods.value.map((selectGood) => selectGood.goodSpecId)
      if (!goodIds.includes(good.goodId) || !goodSpecIds.includes(good.goodSpecId)) {
        selectedGoods.value.push(Object.assign(good, { payNetworkFee: allPayNetworkFee.value }))
      }
    })
  }

  /**
   * 产品删除点击事件
   * @param {Number} index - 产品索引
   */
  const handleDelClick = (index: number) => {
    const goods = selectedGoods.value.splice(index, 1)
    if (goods[0].id) {
      removedFeeStandardIds.value.push(goods[0].id)
    }
  }

  /**
   * 产品批量删除事件
   * @param {Array<SelectedGood>} goods - 要删除的产品列表
   */
  const handleGoodsDel = (goods: Array<SelectedGood>) => {
    goods.forEach((good) => {
      const index = selectedGoods.value.findIndex(
        (selectGood) =>
          selectGood.goodId === good.goodId && selectGood.goodSpecId === good.goodSpecId,
      )
      if (index !== -1) {
        const good = selectedGoods.value.splice(index, 1)[0]
        if (good.id) {
          removedFeeStandardIds.value.push(good.id)
        }
      }
    })
  }

  defineExpose({
    getList: () => {
      const result: OrderAPIRequest.GoodSettleForm['programmeFeeVos'] = []

      const isNoFillPayNetworkFee = selectedGoods.value.some((item) => item.payNetworkFee === '')

      if (isNoFillPayNetworkFee) {
        HMessageBox.error(infoTip.order.goodSettle.noFillPayNeyworkPrice)
        return
      }

      selectedGoods.value.forEach((good) => {
        result.push({
          goodsId: good.goodId,
          goodsName: good.goodName,
          goodsOneTypeId: '',
          goodsThreeTypeId: '',
          goodsTwoTypeId: '',
          goodsSpecId: good.goodSpecId,
          id: good.id,
          payNetworkFee: good.payNetworkFee,
        })
      })

      return result
    },
    setList: (_list: OrderGoodSettleDetail['programmeFeeVos']) => {
      selectedGoods.value = []
      _list.forEach((item) => {
        selectedGoods.value.push({
          goodId: item.goodsId || '',
          goodName: item.goodsName || '',
          payNetworkFee: String(item.payNetworkFee) || '',
          goodSpecId: item.goodsSpecId || '',
          id: item.id || '',
          goodType: item.goodsOneType,
          goodSecondType: item.goodsTwoType,
          goodThreeType: item.goodsThreeType,
          code: item.goodsCode,
          goodSpecName: item.goodsSpec,
          model: item.goodsModel,
        })
      })
    },
    getRemovedFeeStandardIds: () => {
      return [...removedFeeStandardIds.value]
    },
    clearList: () => {
      selectedGoods.value.length = 0
      removedFeeStandardIds.value.length = 0
    },
    setPayNetworkPrice: (price: string) => {
      allPayNetworkFee.value = price
      selectedGoods.value.forEach((item, index) => {
        selectedGoods.value[index].payNetworkFee = price
      })
    },
  })
</script>

<template>
  <el-table :border="true" height="100%" :data="selectedGoods">
    <template #empty>
      <div class="empty-wrapper">
        <div class="text"> 暂无数据 </div>
        <div class="btn-wrapper">
          <h-link @click="selectGoodDrawerVisible = true">选择产品</h-link>
        </div>
      </div>
    </template>

    <!-- 序号 -->
    <el-table-column type="index" width="50" fixed="left" :align="'center'" label="序号" />

    <!-- 编号 -->
    <el-table-column label="编号" width="200" prop="code" show-overflow-tooltip></el-table-column>

    <!-- 产品名称 -->
    <el-table-column
      label="产品名称"
      width="300"
      prop="goodName"
      show-overflow-tooltip
    ></el-table-column>

    <!-- 产品型号 -->
    <el-table-column
      label="产品型号"
      width="120"
      prop="model"
      show-overflow-tooltip
    ></el-table-column>

    <!-- 规格 -->
    <el-table-column
      label="规格"
      width="340"
      prop="goodSpecName"
      show-overflow-tooltip
    ></el-table-column>

    <!-- 产品分类 -->
    <el-table-column label="产品分类" min-width="280">
      <template #default="{ row }">
        <span v-if="row.goodThreeType">{{
          `${row.goodType}、${row.goodSecondType}、${row.goodThreeType}`
        }}</span>
        <span v-else-if="row.goodSecondType">{{ `${row.goodType}、${row.goodSecondType}` }}</span>
        <span v-else-if="row.goodType">{{ row.goodType }}</span>
      </template>
    </el-table-column>

    <!-- 支付网点费用 -->
    <el-table-column label="支付网点费用" width="240">
      <template #default="{ row }">
        <el-input
          placeholder="请输入支付网点费用"
          :model-value="row.payNetworkFee"
          disabled
        ></el-input>
      </template>
    </el-table-column>

    <!-- 操作 -->
    <el-table-column label="操作" fixed="right" width="100">
      <template #default="{ $index }">
        <el-space :size="0" :spacer="spacer">
          <h-link v-if="selectedGoods.length > 1" type="error" @click="handleDelClick($index)"
            >删除</h-link
          >
          <h-link v-if="$index === 0" @click="selectGoodDrawerVisible = true">添加</h-link>
        </el-space>
      </template>
    </el-table-column>

    <good-select-modal
      v-model:visible="selectGoodDrawerVisible"
      :default-selected-ids="selectedGoodIds"
      @confirm="handleGoodAdd"
      @del="handleGoodsDel"
    ></good-select-modal>
  </el-table>
</template>

<style scoped lang="scss">
  :deep(.el-table__empty-block) {
    height: unset !important;

    .el-table__empty-text {
      width: 100%;

      .empty-wrapper {
        position: relative;

        .btn-wrapper {
          position: absolute;
          right: 50px;
          top: 50%;
          transform: translate(50%, -50%);
          height: 16px;
          display: flex;
          align-items: center;
        }
      }
    }
  }

  .pay-network-fee-table-cell-header {
    display: flex;
    column-gap: 5px;
    align-items: center;

    .multiple_btn {
      height: 14px;
      line-height: 14px;
    }
  }
</style>
